package middleware

import (
	"api/internal/types"
	"context"
	jwt "github.com/golangblogs/gojwt"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
)

type AuthTokenMiddleware struct {
}

func NewAuthTokenMiddleware() *AuthTokenMiddleware {
	return &AuthTokenMiddleware{}
}

func (m *AuthTokenMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation
		token := r.Header.Get("token")
		if token == "" {
			resp := types.Response{
				Code: 401,
				Msg:  "token未连接",
				Data: nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		j := jwt.NewJWT("token")
		// parseToken 解析token包含的信息
		claims, err := j.ParseToken(token)
		if err != nil {
			resp := types.Response{
				Code: 401,
				Msg:  "token 无效",
				Data: nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		c := context.WithValue(r.Context(), "userId", claims.ID)
		// Passthrough to next handler if need
		next(w, r.WithContext(c))
	}
}
